<?php

declare(strict_types=1);

namespace app\admin\controller;

use app\admin\service\interface\UserService;
use app\admin\validate\UserValidate;
use think\exception\ValidateException;
use think\facade\Session;
use think\facade\View;
use think\Request;

class Index
{


    /**
     * @var UserService
     */
    public $userservice;
    public function __construct(UserService $userService)
    {
        $this->userservice = $userService;
    }
    public function index()
    {

        return View::fetch('', ['name' => 'ThinkPHP']);
    }
    public function logout(Request $request)
    {
        Session::destroy();
        return redirect((string)url('admin/index/login'));
    }
    public function login(Request $request)
    {
        if ($request->isGet()) {
            return View::fetch();
        } elseif ($request->isPost()) {
            $data= $request->post();
            try {
                validate(UserValidate::class)->failException(true)->check($data);
                if($this->userservice->login_check($data['username'],$data['password'])){
                    Session::set('username', $data['username']);
                }else{
                    return View::fetch('',['error'=> '用户名或密码错误!']+$data);
                }
            } catch (ValidateException $th) {
                $res = $th->getError();
                return View::fetch('',['error'=> $res]+$data);
            }
            return redirect((string)url('admin/index/index'));
        } else {
            throw new \Exception("Error Processing Request");
        }
    }
    public function demo(int $id): string
    {
        return "{$id}";
    }
}
